import AsyncStorage from '@react-native-community/async-storage';

import baseTracker, { ActionData } from '../common/baseTracker';
import { Event } from '../constant/events';
import {
  EVENT_COMMON_PARAM,
  STORAGE_KEY_IS_FIRST_TRY,
  DEVICE_ID,
  APP_NAME,
  CHANNEL,
  APP_VERSION
} from '../constant';
import netInfo from '../common/netInfo';
import { getUserInfo } from '../store/user';

let isFirstTry = false;

// 第一次进来默认是新用户，再次进来则为老用户，和登录注册无关：产品逻辑
AsyncStorage.getItem(STORAGE_KEY_IS_FIRST_TRY).then((res): void => {
  if (!res) {
    isFirstTry = true;
    AsyncStorage.setItem(
      STORAGE_KEY_IS_FIRST_TRY,
      JSON.stringify({ res: true })
    );
    return;
  }
  if (JSON.parse(res).res) {
    AsyncStorage.setItem(
      STORAGE_KEY_IS_FIRST_TRY,
      JSON.stringify({ res: false })
    );
  }
});

const tracker = {
  reportAction: (
    name: Event | string,
    data: ActionData = {},
    immediately: boolean = false
  ): void => {
    console.log('RUA LOG', name, data);
    const { userId } = getUserInfo();
    const eventName: Event = typeof name === 'string' ? { key: name } : name;
    let commonParam = {};
    if (eventName.needCommon) {
      commonParam = {
        ...EVENT_COMMON_PARAM
      };
    }
    baseTracker.reportAction(
      eventName.key,
      {
        ...data,
        ...commonParam,
        userId,
        isFirstTry,
        deviceId: DEVICE_ID,
        appName: APP_NAME,
        channel: CHANNEL,
        appVersion: APP_VERSION,
        netType: netInfo.getNetType()
      },
      immediately
    );
  }
};

export default tracker;
